Dart List operator []
Syntax & Examples


Syntax of List.operator []

The syntax of List.operator [] operator is:

operator [](int index) → E

This operator [] operator of List the object at the given index in the list.

Parameters

ParameterOptional/RequiredDescription
indexrequiredthe index of the object to retrieve from the list


✐ Examples

1 Retrieve element at index 2 from a list of numbers

In this example,

  1. We create a list numbers containing integers.
  2. We use the [] operator to retrieve the element at index 2.
  3. The element at index 2 is assigned to the variable element.
  4. We print the value of element to standard output.

Dart Program

void main() {
  List<int> numbers = [1, 2, 3, 4, 5];
  int element = numbers[2];
  print('Element at index 2: $element');
}

Output

Element at index 2: 3

2 Retrieve element at index 1 from a list of characters

In this example,

  1. We create a list characters containing characters.
  2. We use the [] operator to retrieve the element at index 1.
  3. The element at index 1 is assigned to the variable element.
  4. We print the value of element to standard output.

Dart Program

void main() {
  List<String> characters = ['a', 'b', 'c'];
  String element = characters[1];
  print('Element at index 1: $element');
}

Output

Element at index 1: b

3 Retrieve element at index 0 from a list of names

In this example,

  1. We create a list names containing strings.
  2. We use the [] operator to retrieve the element at index 0.
  3. The element at index 0 is assigned to the variable element.
  4. We print the value of element to standard output.

Dart Program

void main() {
  List<String> names = ['Alice', 'Bob', 'Charlie'];
  String element = names[0];
  print('Element at index 0: $element');
}

Output

Element at index 0: Alice

Summary

In this Dart tutorial, we learned about operator [] operator of List: the syntax and few working examples with output and detailed explanation for each example.